import threading

from pk.WindowManager import WindowManager

class Watu:
    def __init__(self, setupui):
        self.setupUi = setupui
        self.threads = []  # 用于存储所有挖图线程
        self.stop_flag = threading.Event()

    def btn_command(self):
        if any(thread.is_alive() for thread in self.threads):
            self.stop_flag.set()
            for thread in self.threads:
                thread.join(timeout=1)  # 等待所有线程结束
            self.threads = []  # 清空线程列表
            self.setupUi.btn_watu.config(text="自动挖图")
            self.setupUi.add_log("停止自动挖图")
        else:
            if self.setupUi.selectHwnd:
                self.setupUi.add_log("开始自动挖图")
                self.stop_flag.clear()
                for hwnd in self.setupUi.selectHwnd:
                    thread = threading.Thread(target=self.run_command, args=(hwnd,))
                    thread.daemon = True
                    thread.start()
                    self.threads.append(thread)
                self.setupUi.btn_watu.config(text="停止挖图")
            else:
                self.setupUi.add_log("未选择窗口，无法开始自动挖图")
                return

    def run_command(self, hwnd):
        while True:
            while not self.stop_flag.is_set():
                f = WindowManager.findImgAndClick(hwnd, "image/watu/shiyong.png")
                if f:
                    WindowManager.sleep(1)
                    self.setupUi.add_log(f"挖图")
                    break
                else:
                    WindowManager.sleep(0.5)
                    break
